/**
 * Created by GadflyBSD on 16/4/9.
 */
var meta = new Object();
var content = document.getElementsByTagName('meta');
var templatePath = '/Public/template/Customer/';
var wait=60;
for(var i = 0; i < content.length; i++){
	if(content[i].getAttribute('name') == 'Authcode')
		meta.appurl = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'appurl')
		meta.verifyImg = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'upload')
		meta.upload = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'angular')
		meta.angular = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'appId')
		meta.appId = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'timestamp')
		meta.timestamp = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'nonceStr')
		meta.nonceStr = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'signature')
		meta.signature = content[i].getAttribute('content');
}
wx.config({
	debug: false,
	appId: meta.appId,
	timestamp: meta.timestamp,
	nonceStr: meta.nonceStr,
	signature: meta.signature,
	jsApiList: ['scanQRCode', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'openLocation', 'getLocation', 'closeWindow']
});
angular.module('myApp', ['ionic', 'myApp.controllers', 'myApp.services', 'myApp.directive'])
	.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider){
		$ionicConfigProvider.platform.ios.tabs.style('standard');
		$ionicConfigProvider.platform.ios.tabs.position('bottom');
		$ionicConfigProvider.platform.android.tabs.style('standard');
		$ionicConfigProvider.platform.android.tabs.position('bottom');
		$ionicConfigProvider.platform.ios.navBar.alignTitle('center');
		$ionicConfigProvider.platform.android.navBar.alignTitle('center');
		$ionicConfigProvider.platform.ios.views.transition('ios');
		$ionicConfigProvider.platform.android.views.transition('ios');
		$stateProvider
			.state('scanQrCode', {
				url: '/scanQrCode',
				cache: false,
				templateUrl: templatePath + 'scanQrCode.html',
				controller: 'scanQrCodeCtrl'
			})
			.state('survey', {
				url: '/survey',
				cache: false,
				templateUrl: templatePath + 'survey.html',
				controller: 'surveyCtrl'
			})
			.state('bindWaka', {
				url: '/bindWaka',
				cache: false,
				templateUrl: templatePath + 'bindWaka.html',
				controller: 'bindWakaCtrl'
			})
			.state('bindSurvey', {
				url: '/bindSurvey',
				cache: false,
				templateUrl: templatePath + 'bindSurvey.html',
				controller: 'bindSurveyCtrl'
			})
			.state('userInfo', {
				url: '/userInfo',
				cache: false,
				templateUrl: templatePath + 'userInfo.html',
				controller: 'userInfoCtrl'
			})
			.state('billSearch', {
				url: '/billSearch',
				cache: false,
				templateUrl: templatePath + 'billSearch.html',
				controller: 'billSearchCtrl'
			})
			.state('consumeSearch', {
				url: '/consumeSearch',
				cache: false,
				templateUrl: templatePath + 'consumeSearch.html',
				controller: 'consumeSearchCtrl'
			})
			.state('download', {
				url: '/download',
				cache: false,
				templateUrl: templatePath + 'download.html',
				controller: 'downloadCtrl'
			})
			.state('dkf', {
				url: '/dkf',
				cache: false,
				templateUrl: templatePath + 'dkf.html',
				controller: 'dkfCtrl'
			})
			.state('about', {
				url: '/about',
				cache: false,
				templateUrl: templatePath + 'about.html',
				controller: 'aboutCtrl'
			});
		$urlRouterProvider.otherwise('/scanQrCode');
	});
angular.module('myApp.services', [])
	.factory('myService', function($http){
		var http = function(a, b){
			var param = arguments[0]?arguments[0]:{},
				type = arguments[1]?arguments[1]:'post';
			switch(type){
				case 'post':
					return $http.post(meta.angular, angular.extend({ac: 'angular'}, param));
				default:
					return $http.get(meta.angular, angular.extend({ac: 'angular'}, param));
			}
		}
		return {
			getSession: function(refresh){
				"获得用户SESSION数据";
				return http({op: 'getSession', refresh: refresh});
			},
			sendSms: function(mobile, action){
				"发送短信验证码";
				return http({op: 'sendSms', mobile: mobile, action: action}, 'post');
			},
			bindWaka: function(data){
				"汪卡用户绑定汪在线微信号卡";
				return http(angular.extend({op: 'bindWaka'}, data), 'post');
			},
			bindSurvey: function(data){
				return http(angular.extend({op: 'bindSurvey'}, data), 'post');
			},
			getQrcodeData: function(qrcode){
				return http({op: 'getQrcodeData', qrcode: qrcode});
			},
			getShopInfo: function(qrcode){
				"通过二维码扫码结果获得店铺信息";
				return http({op: 'getShopInfo', qrcode: qrcode});
			},
			getSchoolList: function(){
				return http({op: 'getSchoolList'});
			},
			newConsume: function(data){
				"新建消费数据";
				return http(angular.extend({op: 'newConsume'}, data), 'put');
			},
			getUserInfo: function(){
				"获得用户详细数据";
				return http({op: 'getUserInfo'}, 'post');
			},
			setUserInfo: function(data){
				"设置用户详细数据";
				return http(angular.extend({op: 'setUserInfo'}, data), 'post');
			}
		};
	})
	.factory('myPopup', function($ionicPopup){
		"弹出框服务";
		return {
			alert: function(param){
				"alert（警告） 对话框";
				switch(param.type){
					case 'success':
						var title = (typeof param.title == 'null')?'操作成功啦!':param.title;
						var icon = 'ion-checkmark-round';
						break;
					case 'error':
						var title = (typeof param.title == 'null')?'操作失败啦!':param.title;
						var icon = 'ion-close-round';
						break;
					default:
						var title = (typeof param.title == 'null')?'系统操作提示!':param.title;
						var icon = 'ion-information-circled';
						break;
				}
				return $ionicPopup.alert({
					title: title,
					template: '<div class="row"><div class="col col-25"><i class="icon '+icon+'"></i></div><div class="col col-75">'+param.content+'</div></div>'
				});
			}
		}
	});
angular.module('myApp.directive', [])
	.directive('uploadWidget', function(){
		"上传指令";
		return {
			restrict: 'A',
			replace: true,
			scope: {user: '='},
			template: '<a href="#"><img class="img-thumbnail"/></a>',
			link: function(scope, elements, attrs){
				if(attrs.forSrc == 'notImg'){
					elements.find('img').attr('src', 'http://placehold.it/160x120');
				}else{
					elements.find('img').attr('src', attrs.forSrc);
				}
				elements.bind('click', function(){
					wx.config({
						debug: true,
						appId: meta.appId,
						timestamp: meta.timestamp,
						nonceStr: meta.nonceStr,
						signature: meta.signature,
						jsApiList: ['chooseImage', 'previewImage', 'uploadImage', 'downloadImage']
					});
					wx.ready(function(){
						wx.chooseImage({
							count: 1, // 默认9
							sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
							sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
							success: function (res) {
								var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
								elements.attr('src', localIds);
								wx.uploadImage({
									localId: localIds.toString(),
									isShowProgressTips: 1,
									success: function (resu) {
										var serverId = resu.serverId;
										switch(attrs.uploadWidget){
											case 'idcard1':
												scope.user.idcard1 = serverId;
												break;
											case 'idcard2':
												scope.user.idcard2 = serverId;
												break;
											case 'xscard':
												scope.user.xscard = serverId;
												break;
										}
									}
								});
							}
						});
					});
				});
			}
		}
	})
	.directive('buttonWidget', function(myService, myPopup){
		"按钮指令";
		return {
			restrict: 'A',
			link: function(scope, element, attrs){
				switch(attrs.buttonWidget){
					case 'sms':
						"发送短信验证码按钮";
					function sendSmsTimer(){
						"use strict";
						if (wait == 0) {
							element.removeAttr('disabled').text("重新发送短信验证码");
							wait = 60;
						} else {
							element.attr('disabled', 'disabled').text("(" + wait + "秒后)重新发送验证码");
							wait--;
							setTimeout(function(){sendSmsTimer()}, 1000)
						}
					}
						element.bind('click', function(){
							myService.sendSms(attrs.mobile, attrs.ac).success(function(resp){
								myPopup.alert(resp);
							});
							sendSmsTimer();
						});
						break;
					case 'removePreson':
						if(attrs.forRole == 'boss'){
							element.attr('disabled', 'disabled');
						}else{
							element.bind('click', function(){
								myService.removePreson(attrs.forUid).success(function(resp){
									myPopup.alert(resp);
								});
							});
						}
						break;
				}
			}
		}
	})
	.directive('isIdcard', function(){
		"自定义验证是否是合法的身份证号码";
		function validateIdCard(idCard){
			var regIdCard=/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
			if(regIdCard.test(idCard)){
				if(idCard.length==18){
					var idCardWi=new Array( 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ); //将前17位加权因子保存在数组里
					var idCardY=new Array( 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
					var idCardWiSum=0; //用来保存前17位各自乖以加权因子后的总和
					for(var i=0;i<17;i++){
						idCardWiSum+=idCard.substring(i,i+1)*idCardWi[i];
					}
					var idCardMod=idCardWiSum%11;//计算出校验码所在数组的位置
					var idCardLast=idCard.substring(17);//得到最后一位身份证号码
					if(idCardMod==2){
						if(idCardLast=="X"||idCardLast=="x"){
							return true;    //alert("恭喜通过验证啦！");
						}else{
							return false;   //alert("身份证号码错误！");
						}
					}else{
						//用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
						if(idCardLast==idCardY[idCardMod]){
							return true;    //alert("恭喜通过验证啦！");
						}else{
							return false;   //alert("身份证号码错误！");
						}
					}
				}
			}else{
				return false;   //alert("身份证格式不正确!");
			}
		}
		return {
			restrict: "A",
			require: 'ngModel',
			link: function(scope, ele, attrs, ngModelController) {
				ngModelController.$parsers.push(function(value){
					if(validateIdCard(value))
						ngModelController.$setValidity('unique', true);
					else
						ngModelController.$setValidity('unique', false);
					return value;
				});
			}
		}
	})
	.directive('isCode', function($http,$timeout,$window){
		"自定义验证是否是短信验证码";
		return {
			restrict:"A",
			require: 'ngModel',
			link: function(scope, ele, attrs, ngModelController){
				scope.$watch(attrs.ngModel, function(value) {
					if (!value) return;
					$timeout.cancel($window.timer);
					$window.timer = $timeout(function(){
						$http({
							method: 'post',
							url: meta.angular,
							data:{ac: 'validation', op: attrs.isCode, mbcode: value, mobile: attrs.mobile}
						}).success(function(data) {
							ngModelController.$setValidity('unique', data.isUnique); //这个取决于你返回的，其实就是返回一个是否正确的字段，具体的这块可以自己修改根据自己的项目
						}).error(function(data) {
							ngModelController.$setValidity('unique', false);
						});
					}, 1000);
				});
			}
		};
	});
angular.module('myApp.controllers', [])
	.controller('scanQrCodeCtrl', function($scope, $state, $ionicLoading, myService, myPopup){
		$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
		myService.getSession(true).success(function(res){
			if(res.type == 'Success'){
				wx.ready(function(){
					$ionicLoading.hide();
					wx.scanQRCode({
						needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
						scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
						success: function (res) {
							myService.getQrcodeData(res.resultStr).success(function(resp){
								if(resp.type == 'Error'){
									var alertPopup = myPopup.alert(resp);
									alertPopup.then(function(res){
										$state.go('createShop');
									});
								}else if(resp.type == 'survey'){
									$state.go('survey');
								}else{
									$scope.formData = {};
									$scope.scan = resp.data;
									$scope.submit = function(){
										$scope.fromData.sid = resp.data.sid;
										myService.newConsume($scope.fromData).success(function(requery){
											var alertPopup = myPopup.alert(requery);
											alertPopup.then(function(){$state.go('userInfo');});
										})
									}
								}
							});
						}
					});
				});
			}else{
				$ionicLoading.hide();
				var alertPopup = myPopup.alert(res);
				alertPopup.then(function(){$state.go('bindWaka');});
			}
		});

	})
	.controller('bindWakaCtrl', function($scope, $state, $ionicLoading, myService, myPopup){
		$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
		myService.getSession(true).success(function(resp){
			$ionicLoading.hide();
			if(resp.errcode == '0'){
				if(resp.isbind == '0'){
					$scope.formData = {};
					$scope.submit = function(){
						$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
						myService.bindWaka($scope.formData).success(function(resp){
							$ionicLoading.hide();
							var alertPopup = myPopup.alert(resp);
							if(resp.errcode == '0'){
								alertPopup.then(function(){
									wx.ready(function(){
										wx.closeWindow();
									});
								});
							}
						});
					}
				}else{
					var alertPopup = myPopup.alert({
						type: 'Error',
						title: '出错啦!',
						content: '您已经成功绑定汪卡用户,一个微信号只能绑定一个汪卡账户!请不要重复操作!'
					});
					alertPopup.then(function(){
						wx.ready(function(){
							wx.closeWindow();
						});
					});
				}
			}else{
				var alertPopup = myPopup.alert(resp);
				alertPopup.then(function(){
					wx.ready(function(){
						wx.closeWindow();
					});
				});
			}
		});
	})
	.controller('bindSurveyCtrl', function($scope, $state, $ionicLoading, myService, myPopup){
		$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
		$scope.formData = {}
		myService.getSession(true).success(function(resp){
			$ionicLoading.hide();
			if(resp.errcode == '0'){
				if(resp.role == 'student'){
					$scope.submit = function(){
						$ionicLoading.show({
							content: 'Loading',
							animation: 'fade-in',
							showBackdrop: true,
							maxWidth: 200,
							showDelay: 0
						});
						myService.bindSurvey($scope.formData).success(function(resp){
							$ionicLoading.hide();
							var alertPopup = myPopup.alert(resp);
							if(resp.errcode == '0'){
								alertPopup.then(function(){
									wx.ready(function(){
										wx.closeWindow();
									});
								});
							}
						});
					}
				}else if(resp.role == 'survey'){
					var alertPopup = myPopup.alert({
						type: 'Error',
						title: '出错啦!',
						content: '您已经绑定成为尽调员了,一个微信号只能绑定一个尽调员账户!请不要重复操作!'
					});
					alertPopup.then(function(){
						wx.ready(function(){
							wx.closeWindow();
						});
					});
				}else{
					var alertPopup = myPopup.alert({
						type: 'Error',
						title: '出错啦!',
						content: '您的汪卡账户尚未绑定微信!请先绑定微信!'
					});
					alertPopup.then(function(){$state.go('bindWaka');});
				}
			}else{
				var alertPopup = myPopup.alert(resp);
				alertPopup.then(function(){
					wx.ready(function(){
						wx.closeWindow();
					});
				});
			}
		});
	})
	.controller('userInfoCtrl', function($scope, $state, $ionicLoading, myService, myPopup){
		$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
		$scope.user = {
			idcard_url_1: 'notImg',
			idcard_url_2: 'notImg',
			student_card_url: 'notImg',
		}
		myService.getSession(true).success(function(resp){
			$ionicLoading.hide();
			if(resp.errcode != '0'){
				var alertPopup = myPopup.alert(resp);
				alertPopup.then(function(){$state.go('bindWaka');});
			}else{
				$scope.user = angular.extend($scope.user, resp.data);
				$scope.school = resp.school;
				$scope.survey = resp.survey;
				$scope.submit = function(){
					$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
					myService.setUserInfo($scope.user).success(function(resp){
						$ionicLoading.hide();
						myPopup.alert(resp);
					})
				}
			}
		});
	})
	.controller('billSearchCtrl', function(){})
	.controller('consumeSearchCtrl', function(){})
	.controller('downloadCtrl', function(){})
	.controller('dkfCtrl', function(){})
	.controller('aboutCtrl', function($scope, $http){
		$http({
			method: 'GET',
			url: 'http://m.waka.cn/App/angular.html',
			params: {ac: 'tttt'}
		}).success(function(resp){
			alert(resp);
		})
	})
	.controller('NavCtrl', ['$scope', '$ionicActionSheet', '$state', function($scope, $ionicActionSheet, $state){
		$scope.scanQrCode = function(){
			"use strict";
			$state.go('scanQrCode');
		}
		$scope.openMenu0 = function(){
			$ionicActionSheet.show({
				buttons: [
					{text: '绑定微信'},
					{text: '绑定尽调员'},
					{text: '个人信息'},
					{text: '账单查询'},
					{text: '消费查询'},
				],
				titleText: '账户&账单管理子菜单',
				buttonClicked: function(index){
					switch(index){
						case 0:
							$state.go('bindWaka');
							break;
						case 1:
							$state.go('bindSurvey');
							break;
						case 2:
							$state.go('userInfo');
							break;
						case 3:
							$state.go('billSearch');
							break;
						case 4:
							$state.go('consumeSearch');
							break;
					}
					return true;
				}
			});
		};
		$scope.openMenu1 = function(){
			$ionicActionSheet.show({
				buttons: [
					{text: '客户端下载'},
					{text: '联系客服'},
					{text: '关于我们'},
				],
				titleText: '关于&帮助子菜单',
				buttonClicked: function(index){
					switch(index){
						case 0:
							$state.go('download');
							break;
						case 1:
							$state.go('dkf');
							break;
						case 2:
							$state.go('about');
							break;
					}
					return true;
				}
			});
		};
	}]);